package com.jt.safe.extension

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.jt.safe.base.BaseDataResponse
import com.jt.safe.base.BaseQueryResultResponse
import com.jt.safe.state.ViewState
import com.jt.safe.viewmodel.BaseViewModel
import kotlinx.coroutines.launch

/**
 * net request
 * @param request request method
 * @param viewState request result
 */

fun <T> BaseViewModel.launchRequest(
    request: suspend () -> BaseDataResponse<T>,
    viewState: MutableLiveData<ViewState<T>>
) {
    viewModelScope.launch {
        runCatching {
            viewState.value = ViewState.onHubLoading()
            request()
        }.onSuccess {
            viewState.paresResult(it)
        }.onFailure {
            viewState.paresException(it)
        }
    }
}

fun <T> BaseViewModel.launchRequestQueryResult(
    request: suspend () -> BaseQueryResultResponse<T>,
    viewState: MutableLiveData<ViewState<T>>
) {
    viewModelScope.launch {
        runCatching {
            viewState.value = ViewState.onHubLoading()
            request()
        }.onSuccess {
            viewState.paresResult(it)
        }.onFailure {
            viewState.paresException(it)
        }
    }
}

